package category

import (
	"context"
	"mall/common/excption"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"
	"mall/services/product/rpc/internal/mapper/entity"
	"time"

	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ModifyCategoryInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewModifyCategoryInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyCategoryInfoLogic {
	return &ModifyCategoryInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ModifyCategoryInfoLogic) ModifyCategoryInfo(in *pb.ModifyCategoryInfoDTO) (*pb.EmptyObj, error) {
	// 1.check request dto
	categoryMapper, checkRequestErr := l.checkRequestDTO(in)
	if checkRequestErr != nil {
		return nil, checkRequestErr
	}
	// 2.update db
	saveErr := l.saveDB(in, categoryMapper)
	if saveErr != nil {
		return nil, saveErr
	}
	// 3.return obj
	return &pb.EmptyObj{}, nil
}

func (l *ModifyCategoryInfoLogic) saveDB(in *pb.ModifyCategoryInfoDTO, categoryMapper *mapper.CategoryMapper) error {
	now := time.Now()
	categoryEntity := entity.CategoryEntity{
		CategoryId: in.CategoryId,
		UpdateTime: now,
		ShopId:     in.ShopId,
		ParentId:   in.ParentId,
		Name:       in.Name,
		Desc:       in.Desc,
		Path:       in.Path,
		Icon:       in.Icon,
		ImgUrl:     in.ImgUrl,
		Level:      int64(in.Level),
		Seq:        int64(in.Seq),
	}
	updateErr := categoryMapper.UpdateCtx(l.svcCtx.DBEngin, categoryEntity)
	if updateErr != nil {
		return updateErr
	}
	return nil
}

func (l *ModifyCategoryInfoLogic) checkRequestDTO(in *pb.ModifyCategoryInfoDTO) (*mapper.CategoryMapper, error) {
	categoryMapper := mapper.NewCategoryMapper(l.ctx)
	categoryBO := bo.CategoryBO{CategoryId: in.CategoryId}
	selectCountCtx, err := categoryMapper.SelectCountCtx(l.svcCtx.DBEngin, categoryBO)
	if err != nil {
		return nil, err
	}
	if selectCountCtx <= 0 {
		return nil, excption.NewErrCode(constans.CategoryNotExistErr)
	}
	return categoryMapper, nil
}
